package com.devilvan.customOutputFormat;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

public class CustomOutputFormatMain extends Configured implements Tool {
    @Override
    public int run(String[] args) throws Exception {
        FileSystem fileSystem = FileSystem.get(super.getConf());
        if (fileSystem.exists(new Path(args[1]))) fileSystem.delete(new Path(args[1]), true);
        Job job = Job.getInstance(super.getConf(), CustomOutputFormatMain.class.getSimpleName());
        job.setJarByClass(this.getClass());
        job.setInputFormatClass(TextInputFormat.class);
        TextInputFormat.addInputPath(job, new Path(args[0]));
        job.setMapperClass(CustomOutputFormatMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);
        // 不需要Reduce了
        job.setOutputFormatClass(CustomOutputFormat.class);
        CustomOutputFormat.setOutputPath(job,new Path(args[1]));
        job.setNumReduceTasks(Integer.parseInt(args[2]));
        boolean flag = job.waitForCompletion(true);
        return flag ? 0 : 1;
    }

    public static class CustomOutputFormatMapper extends Mapper<LongWritable, Text,Text, NullWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            context.write(value,NullWritable.get());
        }
    }

    public static void main(String[] args) throws Exception {
        int run = ToolRunner.run(new Configuration(), new CustomOutputFormatMain(), args);
        System.exit(run);
    }
}
